package com.jds.test.proto;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by sunyuming on 18/8/1.
 */
public class ClientHandler4Heart extends SimpleChannelInboundHandler<MyBaseProto.BaseProto> {

    //接受服务端发来的消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyBaseProto.BaseProto msg) throws Exception {

        if("Heartbeat".equals(msg.getMsg())) {
            System.out.println("* CLIENT receive back heart");
        } else {
            System.out.println("SERVER'S general msg RESPONSE ： "+ msg.toString());
        }
    }

    //与服务器建立连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //给服务器发消息
        MyBaseProto.BaseProto.Builder builder = MyBaseProto.BaseProto.newBuilder();
        builder.setCode(1);
        builder.setMsg("hello");
        ctx.channel().writeAndFlush(builder.build());
    }

    //与服务器断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭管道
        ctx.channel().close();
        //打印异常信息
        cause.printStackTrace();
    }

}
